<script setup lang="ts">
import Topic from '@/components/Topic.vue'
import { ref, computed } from 'vue'
import Reply from '@/components/Reply.vue'
import { Promotion } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import {
  userAddCommentService,
  userGetCommentListService,
  userGetTopicDetailService
} from '@/api/user'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const topicId = ref(route.params.id)
console.log(topicId.value)

const topic = ref({
  id: 1,
  title: 'TCP和UDP有什么区别',
  publisher: '胡清钟',
  identify: '教师',
  content: '我觉得意大利面就该拌32号混凝土，因为螺丝钉的长度会直接影响挖掘机的扭矩',
  image: '',
  createTime: '2024-12-04',
  watch: '10',
  reply: '2',
  like: '5'
})

interface Comment {
  id: number
  publisher: string
  content: string
  createTime: string
  identify: string
  avatar: string
}

const commentList = ref<Comment[]>([])

enum identifyType {
  'teacher' = 'success',
  'student' = 'primary'
}

enum identifyCN {
  'teacher' = '老师',
  'student' = '学生'
}

// 我的评论
const myComment = ref('')

// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = 5
// 总记录数
const totalRecords = ref(0)
// 判断是否已经加载到底
const noMoreData = computed(() => {
  console.log(commentList.value.length, totalRecords.value)
  return commentList.value.length >= totalRecords.value
})

const loading = ref(false)
const disabled = computed(() => loading.value)

const getTopicDetail = async () => {
  const res = await userGetTopicDetailService(topicId.value)
  topic.value = res.data.data
}

getTopicDetail()

const getCommentList = async () => {
  if (loading.value) return // 防止重复请求
  loading.value = true

  const res = await userGetCommentListService(currentPage.value, topicId.value)
  const data = res.data.data

  // 更新总记录数
  totalRecords.value = data.total // 假设总记录数字段名为 totalRecords

  // 如果返回的数据存在评论，直接赋值到 commentList
  if (data.records.length > 0) {
    if (currentPage.value === 1) {
      // 如果是第一页，重新赋值，不进行拼接
      commentList.value = data.records
    } else {
      // 如果是分页加载，拼接新数据
      commentList.value = [...commentList.value, ...data.records]
    }
  }

  loading.value = false
}

getCommentList()

// 加载更多评论
const load = async () => {
  if (loading.value || noMoreData.value) return // 如果正在加载或者没有更多数据，则不执行

  currentPage.value += 1
  await getCommentList()
}

// 滚动事件监听
const onScroll = () => {
  if (window.innerHeight + window.scrollY >= document.body.scrollHeight - 100) {
    load()
  }
}

// 监听滚动事件
window.addEventListener('scroll', onScroll)

// 发表我的评论
const submitMyComment = async () => {
  if (myComment.value.trim() === '') {
    ElMessage.warning('评论内容不能为空')
    return
  }
  await userAddCommentService(myComment.value, topicId.value)
  currentPage.value = 1
  await getCommentList() // 更新评论列表
  await getTopicDetail() // 更新话题详情
  // 清空评论框
  myComment.value = ''
}

const userStore = useUserStore()
</script>

<template>
  <div id="main-topicContent">
    <Topic class="topic">
      <template #title>{{ topic.title }}</template>
      <template #publisher>{{ topic.publisher }}</template>
      <template #identify>
        <el-tag :type="identifyType[topic.identify]" style="margin-left: 5px"
          >{{ identifyCN[topic.identify] }}
        </el-tag>
      </template>
      <template #content>{{ topic.content }}</template>
      <template #image>
        <img
          v-if="topic.image"
          :src="topic.image"
          style="height: 180px; width: auto; border-radius: 5px"
          alt=""
        />
      </template>
      <template #createTime>{{ topic.createTime }}</template>
      <template #watch>{{ topic.watch }}</template>
      <template #reply>{{ topic.reply }}</template>
      <template #like>{{ topic.like }}</template>
    </Topic>
    <h3 style="margin-left: 20px">评论区</h3>
    <div class="reply-area">
      <el-scrollbar class="infinite-list-wrapper" style="overflow: auto">
        <div v-infinite-scroll="load" class="list" :infinite-scroll-disabled="disabled">
          <div v-for="comment in commentList" :key="comment.id">
            <Reply>
              <template #publisher>{{ comment.publisher }}</template>
              <template #avatar>
                <img :src="comment.avatar" id="avatar" alt="" />
              </template>
              <template #content>{{ comment.content }}</template>
              <template #createTime>{{ comment.createTime }}</template>
              <template #identify>
                <el-tag :type="identifyType[comment.identify]" style="margin-left: 5px"
                  >{{ identifyCN[comment.identify] }}
                </el-tag>
              </template>
            </Reply>
            <el-divider />
          </div>
          <!-- 没有更多数据时显示提示 -->
          <div v-if="noMoreData" class="no-more-data">
            <el-alert title="没有更多数据了" type="info" center />
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="remark-area">
      <img :src="userStore.getAvatar()" id="avatar" alt="" />
      <el-input
        style="flex: 1; height: 50px; margin-left: 10px"
        maxlength="50"
        placeholder="请发表你的见解吧"
        show-word-limit
        v-model="myComment"
        @keyup.enter="submitMyComment"
      ></el-input>
      <el-button
        :icon="Promotion"
        circle
        style="height: 50px; width: 50px; right: 0; position: relative; margin-left: 10px"
        type="primary"
        @click="submitMyComment"
      ></el-button>
    </div>
  </div>
</template>

<style scoped>
#main-topicContent {
  position: relative;
  width: 100%;
}

.reply-area {
  background-color: #fff;
  margin: 20px;
  overflow: hidden;
  border-radius: 10px;
}

.remark-area {
  padding: 10px;
  backdrop-filter: blur(10px);
  webkit-backdrop-filter: blur(10px);
  margin: 20px;
  display: flex;
  align-items: center;
  width: 95%;
  height: 60px;
  position: relative;
  bottom: 0;
  background-color: #fff;
  border-radius: 10px;
}

#avatar {
  overflow: hidden;
  height: 40px;
  width: 40px;
  clip-path: circle(50% at 50% 50%);
}

.infinite-list-wrapper {
  height: 55vh;
}

.no-more-data {
  text-align: center;
  margin-top: 20px;
}
</style>
